﻿using Magicodes.WeiChat.Data.Models;
using Magicodes.WeiChat.Data.Models.WeiChat;
using Magicodes.WeChat.SDK;
using Magicodes.WeChat.SDK.Apis.User;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Ajax;
using Magicodes.WeiChat.Models;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Magicodes.WeChat.SDK.Apis.Message.Input;

namespace Magicodes.WeiChat.Controllers
{
    public class GroupMessageController : TenantBaseController<WeiChat_User>
    {
        public ActionResult Send(int? type)
        {
            ViewBag.UserGroupId = new SelectList(db.WeiChat_UserGroups.ToList(), dataValueField: "GroupId", dataTextField: "Name");
            var log = new WeiChat_GroupMessageLog();
            var user = db.Users.Find(UserId);
            if (!string.IsNullOrEmpty(user.OpenId))
            {
                ViewBag.WeChatUser = db.WeiChat_Users.Find(user.OpenId);
            }
            return View(log);
        }

        [HttpPost]
        public ActionResult Send(WeiChat_GroupMessageLog model, bool isPreview = true)
        {
            var res = new AjaxResponse()
            {
                Success = true,
                Message = "发送成功！"
            };
            if (string.IsNullOrWhiteSpace(model.MediaId))
            {
                res.Success = false;
                res.Message = "请选择素材！";
            }
            else
            {
                try
                {
                    if (isPreview)
                    {
                        #region 发送预览
                        if (string.IsNullOrWhiteSpace(model.WXName) && (!model.IsUseOpenId))
                        {
                            res.Success = false;
                            res.Message = "请填写接收者微信账号！";
                        }
                        else
                        {
                            PreviewInputBase sendData = null;
                            switch (model.MessageType)
                            {
                                case SendMessageTypes.Text:
                                    sendData = new PreviewTextInput()
                                    {
                                        Text = new PreviewTextInput.TextInfo()
                                        {
                                            Content = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.Image:
                                    sendData = new PreviewImageInput()
                                    {
                                        Image = new PreviewImageInput.ImageInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.Voice:
                                    sendData = new PreviewVoiceInput()
                                    {
                                        Voice = new PreviewVoiceInput.VoiceInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.Video:
                                    sendData = new PreviewMPVideoInput()
                                    {
                                        MPVideo = new PreviewMPVideoInput.MPVideoInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.News:
                                    sendData = new PreviewNewsInput()
                                    {
                                        News = new PreviewNewsInput.NewsInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                default:
                                    break;
                            }
                            if (model.IsUseOpenId && !string.IsNullOrEmpty(model.OpenId))
                            {
                                sendData.ToUser = model.OpenId;
                            }
                            else
                            {
                                sendData.ToWXName = model.WXName;
                            }
                            WeChatApisContext.Current.MessageApi.Preview(sendData);
                        }
                        #endregion

                    }
                    else
                    {
                        var q = db.WeiChat_Users.AsQueryable();
                        var isSendByOpenIds = false;
                        if (model.SexType != SexTypes.All)
                        {
                            var sexType = (WeChatSexTypes)((int)model.SexType - 1);
                            q = q.Where(p => p.Sex == sexType);
                            isSendByOpenIds = true;
                        }
                        if (isSendByOpenIds)
                        {
                            if (!string.IsNullOrEmpty(model.UserGroupId))
                            {
                                var groupId = Convert.ToInt32(model.UserGroupId);
                                q = q.Where(p => p.GroupId == groupId);
                            }
                            var openIds = q.Select(p => p.OpenId).ToArray();
                            if (openIds == null || openIds.Length == 0)
                            {
                                res.Success = false;
                                res.Message = "没有找到符合该条件的粉丝，请手动同步粉丝后或者修改条件后再试！";
                            }
                            else
                            {
                                #region 根据OpendId群发
                                SendInputBase sendData = null;
                                switch (model.MessageType)
                                {
                                    case SendMessageTypes.Text:
                                        sendData = new SendTextInput()
                                        {
                                            Text = new SendTextInput.TextInfo()
                                            {
                                                Content = model.MediaId
                                            },
                                        };
                                        break;
                                    case SendMessageTypes.Image:
                                        sendData = new SendImageInput()
                                        {
                                            Image = new SendImageInput.ImageInfo()
                                            {
                                                MediaId = model.MediaId
                                            },
                                        };
                                        break;
                                    case SendMessageTypes.Voice:
                                        sendData = new SendVoiceInput()
                                        {
                                            Voice = new SendVoiceInput.VoiceInfo()
                                            {
                                                MediaId = model.MediaId
                                            },
                                        };
                                        break;
                                    case SendMessageTypes.Video:
                                        sendData = new SendVideoInput()
                                        {
                                            Video = new SendVideoInput.VideoInfo()
                                            {
                                                MediaId = model.MediaId
                                            },
                                        };
                                        break;
                                    case SendMessageTypes.News:
                                        sendData = new SendNewsInput()
                                        {
                                            News = new SendNewsInput.NewsInfo()
                                            {
                                                MediaId = model.MediaId
                                            },
                                        };
                                        break;
                                    default:
                                        break;
                                }
                                sendData.ToUsers = openIds;

                                var result = WeChatApisContext.Current.MessageApi.Send(sendData);
                                SetModel(model, default(long));
                                res.Success = result.IsSuccess();
                                res.Message = result.Message;
                                model.IsSuccess = res.Success;
                                model.Message = res.Message;
                                db.WeiChat_GroupMessageLogs.Add(model);
                                db.SaveChanges();
                                #endregion
                            }

                        }
                        else
                        {
                            #region 根据分组群发或者全部群发
                            SendAllInputBase sendData = null;
                            switch (model.MessageType)
                            {
                                case SendMessageTypes.Text:
                                    sendData = new SendAllTextInput()
                                    {
                                        Text = new SendAllTextInput.TextInfo()
                                        {
                                            Content = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.Image:
                                    sendData = new SendAllImageInput()
                                    {
                                        Image = new SendAllImageInput.ImageInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.Voice:
                                    sendData = new SendAllVoiceInput()
                                    {
                                        Voice = new SendAllVoiceInput.VoiceInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.Video:
                                    sendData = new SendAllMPVideoInput()
                                    {
                                        MPVideo = new SendAllMPVideoInput.MPVideoInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                case SendMessageTypes.News:
                                    sendData = new SendAllNewsInput()
                                    {
                                        News = new SendAllNewsInput.NewsInfo()
                                        {
                                            MediaId = model.MediaId
                                        },
                                    };
                                    break;
                                default:
                                    break;
                            }
                            if (!string.IsNullOrWhiteSpace(model.UserGroupId))
                            {
                                sendData.Filter = new SendAllInputBase.FilterInfo()
                                {
                                    GroupId = Convert.ToInt32(model.UserGroupId),
                                    IsToAll = false
                                };
                            }
                            else
                            {
                                sendData.Filter = new SendAllInputBase.FilterInfo()
                                {
                                    IsToAll = true
                                };
                            }

                            var result = WeChatApisContext.Current.MessageApi.SendAll(sendData);
                            SetModel(model, default(long));
                            res.Success = result.IsSuccess();
                            res.Message = result.Message;
                            if (res.Success)
                            {
                                res.Message = "发送成功，任务已创建，如果粉丝人数比较多，消息接收会有一定的延迟。";
                            }
                            model.IsSuccess = res.Success;
                            model.Message = res.Message;
                            db.WeiChat_GroupMessageLogs.Add(model);
                            db.SaveChanges();
                            #endregion
                        }
                    }
                }
                catch (Exception ex)
                {
                    res.Success = false;
                    res.Message = "发送失败！" + ex.Message;
                    model.IsSuccess = res.Success;
                    model.Message = res.Message;
                    db.WeiChat_GroupMessageLogs.Add(model);
                    db.SaveChanges();
                }
            }
            return Json(res);
        }
    }
}